package com.lovcreate.shop.mapp.util;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author 高博
 * @version 1.0
 * @Time 2016-12-22 15:57:15
 * @Descrption ip通用工具
 */
public class IPUtils {

    private final static Logger logger = LoggerFactory.getLogger(IPUtils.class);

    private static final String IP = "IP";

    private static final String[] ALLOW_IP = new String[]{"101.201.116.50", "60.205.56.105"};


    public static Boolean allow() {

        Map<String, String> map = getLocalIP();
        if (!map.isEmpty()) {
            for (String key : ALLOW_IP) {
                if (map.containsKey(key)) {
                    logger.info("允许执行定时任务");
                    return true;
                }
            }
        }
        return false;

    }

    public static Map<String, String> getLocalIP() {

        Map<String, String> map = Maps.newHashMap();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        map.put(ip, IP);
                        logger.info("IPV4地址:{}", map);
                    }
                }
            }
        } catch (SocketException e) {
            logger.info("获取本机IP失败:{}", e);
        }
        return map;
    }

    public static void main(String[] args) {


        System.out.println(allow());


    }
}
